// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");

const buildRoutesTree = (data) => {
	const map = {};
	const result = [];

	data.forEach(el => {
		map[el.id] = { ...el, create: moment(el.create).format("YYYY-MM-DD HH:mm:ss"), children: [] };
	});

	data.forEach(el => {
		if (el.parentId) {
			map[el.parentId].children.push(map[el.id]);
		} else {
			result.push(map[el.id]);
		}
	});

	return result;
};

// 获取所有路由
exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `select * from ${table} where name != 'pagesMg'`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("暂无路由!");
		const data = buildRoutesTree(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 新增
exports.Add = async (req, res, table) => {
	const { path, name, component, meta, redirect, parentId, icon, title, permission } = req.body;
	const info = [path, name, component, meta, redirect, parentId, icon, title, permission];

	try {
		const sqlStr1 = `SELECT * FROM ${table} WHERE path = ? OR name = ? OR title = ?`;
		const [results1] = await mysql.query(sqlStr1, [path, name, title]);
		if (results1.length > 0) return res.error("路径或名或标题已被占用,请更换!");

		const sqlStr2 = `INSERT INTO ${table} SET ?`;
		const [results2] = await mysql.query(sqlStr2, info);
		if (results2.affectedRows !== 1) return res.error("新增失败");

		return res.success("新增成功");
	} catch (err) {
		return res.error(err);
	}
};

// 修改
exports.Update = async (req, res, table) => {
	const { path, name, icon, title, id } = req.body;
	const info = [path, name, icon, title, id];

	try {
		const sqlStr = `UPDATE ${table} SET path=?, name=?, icon=?, title=? WHERE id=?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("修改失败");
		return res.success("修改成功");
	} catch (err) {
		return res.error(err);
	}
};